package com.valuegroup.smarttodo.ui.programme.summarize;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.flexbox.FlexboxLayout;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.common.CommonRecyclerAdapter;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.SumContent;
import com.valuegroup.smarttodo.data.model.SumTopic;
import com.valuegroup.smarttodo.data.model.Summarize;
import com.valuegroup.smarttodo.data.vo.SumContentTopicVo;
import com.valuegroup.smarttodo.plugins.chip.Chip;
import com.valuegroup.smarttodo.plugins.chip.OnCloseClickListener;
import com.valuegroup.smarttodo.plugins.chip.OnSelectClickListener;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddActivity;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddEditText;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddInputCheckRule;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QuickAddEditorCallback;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QuickAddHolder;
import com.valuegroup.smarttodo.util.AlertUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SumContentActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.labHeaderTitle)
    TextView labHeaderTitle;
    @BindView(R.id.labTitle)
    TextView labTitle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private Long DATA_ID;
    private Integer DATA_POSITION;
    private Summarize DATA;
    private SumContentTopicAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sum_content);
        ButterKnife.bind(this);

        // 初始化工具条
        setSupportActionBar(toolbar);
        // 隐藏Toolbar的标题栏
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getSummarizeService().getSummarizeDao().load(DATA_ID);
        if (DATA == null) {
            AlertUtils.showToast(this, R.string.not_found_record);
            finish();
            return;
        }

        initView();

    }

    private void initView() {
        adapter = new SumContentTopicAdapter(this, loadData());
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        labTitle.setText(DATA.getTitle());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_sum_content, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(@NonNull Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.m1:
                showDialog();
                break;
            case R.id.m2:
                AlertUtils.delOrderDialog(SumContentActivity.this,
                        getResources().getString(R.string.alt_del_sum),
                        (dialog, which) -> {
                            ServiceFactory.getInstance().getSummarizeService().delSum(DATA.getId());
                            finishAfterTransition();
                        });
                break;
            case R.id.m3:
                AlertUtils.delOrderDialog(SumContentActivity.this,
                        getResources().getString(R.string.alt_clear_topic),
                        (dialog, which) -> {
                            ServiceFactory.getInstance().getSumContentService().clearTopic(DATA.getId());
                            refreshAllData();
                        });
                break;
        }
        return false;
    }

    private void refreshAllData() {
        // 刷新列表数据
        adapter.refreshListData(loadData());
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);
    }

    private List<SumContentTopicVo> loadData() {
        return ServiceFactory.getInstance().getSumContentService().findSumContent(DATA.getId());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        refreshAllData();
    }

    @OnClick({R.id.btnBack})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                finishAfterTransition();
                break;

        }
    }

    private Dialog mShareDialog;
    private FlexboxLayout fbAll;
    private FlexboxLayout fbChose;
    private boolean isDelStatus = false;

    private void showDialog() {
        if (mShareDialog == null) {
            initShareDialog();
        }
        initDialogData();
        mShareDialog.show();
    }

    private void initDialogData() {
        inflateTopic();
    }

    /**
     * 初始化弹出框
     */
    private void initShareDialog() {
        mShareDialog = new Dialog(this, R.style.dialog_bottom_full);
        mShareDialog.setCanceledOnTouchOutside(true);
        mShareDialog.setCancelable(true);
        Window window = mShareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.share_animation);
        View view = View.inflate(this, R.layout.dialog_sum_topic, null);
        fbAll = view.findViewById(R.id.fbAll);
        fbChose = view.findViewById(R.id.fbChose);
        EditText editTagAdd = view.findViewById(R.id.editTagAdd);
        view.findViewById(R.id.btnDetermine).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mShareDialog != null && mShareDialog.isShowing()) {
                    mShareDialog.dismiss();
                    refreshAllData();
                }
            }
        });
        editTagAdd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (!hasFocus) {
                    // 失去焦点
                    if (!TextUtils.isEmpty(editTagAdd.getText().toString())) {
                        ServiceFactory.getInstance().getSumContentService().addSumTopicAndBind(editTagAdd.getText().toString(), DATA.getId());
                        editTagAdd.setText("");
                        inflateTopic();
                    }
                }
            }
        });

        editTagAdd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    if (!TextUtils.isEmpty(v.getText())) {
                        ServiceFactory.getInstance().getSumContentService().addSumTopicAndBind(editTagAdd.getText().toString(), DATA.getId());

                        // 清空数据
                        v.setText(null);
                        inflateTopic();
                    }
                }
                return true;
            }
        });
        TextView btnDel = view.findViewById(R.id.btnDel);
        btnDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isDelStatus = !isDelStatus;
                inflateTopic();
                btnDel.setText(getResources().getText(isDelStatus ? R.string.op_cancel : R.string.op_delete));
            }
        });

        window.setContentView(view);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
    }


    private void inflateTopic() {
        // 已选标签
        fillTopicChose();
        // 全部标签
        if (isDelStatus) {
            fillTopicAllForDel();
        } else {
            fillTopicAll();
        }
    }

    private void fillTopicChose() {
        fbChose.removeAllViews();

        // 查询已选取的主题
        List<Long> choiceTopic = ServiceFactory.getInstance().getSumContentService().findChoiceTopic(DATA.getId());
        // 所有主题
        List<SumTopic> topicList = ServiceFactory.getInstance().getSumTopicService().findSumTopic();
        for (SumTopic topic : topicList) {

            if (!choiceTopic.contains(topic.getId())) {
                continue;
            }

            // 只处理已选择的主题
            View tagView = getLayoutInflater().inflate(R.layout.single_tag, null);
            Chip tag = tagView.findViewById(R.id.tag);
            tag.setChipText(topic.getTitle());
            tag.setTagId(topic.getId());
            tag.setClosable(true);
            tag.setOnCloseClickListener(new OnCloseClickListener() {
                @Override
                public void onCloseClick(View v, Long topicId) {
                    AlertUtils.delOrderDialog(SumContentActivity.this,
                            String.format(getResources().getString(R.string.alt_del_topic), topic.getTitle()),
                            (dialog, which) -> {
                                ServiceFactory.getInstance().getSumContentService().delTopic(DATA.getId(), topicId);
                                inflateTopic();
                            });
                }
            });

            fbChose.addView(tagView);
        }
    }

    private void fillTopicAll() {
        fbAll.removeAllViews();

        // 查询已选取的主题
        List<Long> choiceTopic = ServiceFactory.getInstance().getSumContentService().findChoiceTopic(DATA.getId());
        // 所有主题
        List<SumTopic> topicList = ServiceFactory.getInstance().getSumTopicService().findSumTopicOnUsable();
        for (SumTopic topic : topicList) {

            // 只处理已选择的主题
            View tagView = getLayoutInflater().inflate(R.layout.single_tag, null);
            Chip tag = tagView.findViewById(R.id.tag);
            tag.setChipText(topic.getTitle());
            tag.setTagId(topic.getId());

            if (choiceTopic.contains(topic.getId())) {
                tag.setSelected(true);
            }
            tag.setOnSelectClickListener(new OnSelectClickListener() {
                @Override
                public void onSelectClick(View v, Long topicId, boolean selected) {
                    if (selected) {
                        SumContent s = ServiceFactory.getInstance().getSumContentService().getDefaultSumContent(DATA.getId(), topicId);
                        ServiceFactory.getInstance().getSumContentService().getSumContentDao().save(s);
                    } else {
                        AlertUtils.delOrderDialog(SumContentActivity.this,
                                String.format(getResources().getString(R.string.alt_del_topic), topic.getTitle()),
                                (dialog, which) -> {
                                    ServiceFactory.getInstance().getSumContentService().delTopic(DATA.getId(), topicId);
                                    inflateTopic();
                                });
                    }
                    inflateTopic();
                }
            });

            fbAll.addView(tagView);
        }
    }

    private void fillTopicAllForDel() {
        fbAll.removeAllViews();

        // 查询已选取的主题
        List<Long> choiceTopic = ServiceFactory.getInstance().getSumContentService().findChoiceTopic(DATA.getId());
        // 所有主题
        List<SumTopic> topicList = ServiceFactory.getInstance().getSumTopicService().findSumTopicOnUsable();
        for (SumTopic topic : topicList) {

            // 只处理已选择的主题
            View tagView = getLayoutInflater().inflate(R.layout.single_tag, null);
            Chip tag = tagView.findViewById(R.id.tag);
            tag.setChipText(topic.getTitle());
            tag.setTagId(topic.getId());

            tag.setClosable(true);
            tag.setOnCloseClickListener(new OnCloseClickListener() {
                @Override
                public void onCloseClick(View v, Long topicId) {
                    AlertUtils.delOrderDialog(SumContentActivity.this,
                            String.format(getResources().getString(R.string.alt_del_topic), topic.getTitle()),
                            (dialog, which) -> {
                                // 含关联先
                                ServiceFactory.getInstance().getSumContentService().delOrDisableTopic(topicId, DATA.getId());
                                inflateTopic();
                            });
                }
            });

            fbAll.addView(tagView);
        }
    }

    class SumContentTopicAdapter extends CommonRecyclerAdapter<SumContentTopicVo> {

        public SumContentTopicAdapter(Context context, List<SumContentTopicVo> data) {
            super(context, data);
            setMainLayoutId(R.layout.item_sum_content_topic);
        }

        @Override
        public void bindHeadView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindBottomView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindMainView(BaseViewHolder v, int position) {
            SumContentTopicVo data = getData(position);

            Chip topic = v.getView(R.id.topic);
            topic.setChipText(data.getTopicTitle());

            v.setText(R.id.labContent, data.getContent());
            v.setText(R.id.labContentDt, DateUtils.date2str(data.getUpdatedDt(), DateUtils.F13));
            v.setViewVisibility(R.id.labContentDt, true);

            v.getView(R.id.contentLayout).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    QucikAddActivity.openEditorNoRepeat(
                            SumContentActivity.this,
                            new QuickAddEditorCallback() {
                                @Override
                                public void onCancel() {
                                }

                                @Override
                                public void onSubmit(String content) {
                                    if (TextUtils.isEmpty(content)) {
                                        return;
                                    }
                                    data.setContent(content);
                                    ServiceFactory.getInstance().getSumContentService().updateContent(data.getId(), content);
                                    notifyItemChanged(position, data);
                                }

                                @Override
                                public void onAttached(ViewGroup rootView) {
                                    QucikAddEditText etContent = rootView.findViewById(R.id.quick_add_task_content_edt);
                                    etContent.setText(data.getContent());
                                }
                            },
                            new QuickAddHolder(QuickAddHolder.QuickAddType.MULTI_INSERT_FOR_SUM),
                            new QucikAddInputCheckRule(800, 2),
                            Gravity.CENTER);
                }
            });

        }

        @Override
        public void bindAppendView(BaseViewHolder v, int position) {

        }
    }
}
